package com.example.demo.service.impl;

import com.example.demo.enums.DBConnectionTypeEnum;
import com.example.demo.mapper.DBConnectionMapper;
import com.example.demo.entity.DBConnection;
import com.example.demo.service.DBConnectionService;
import com.example.demo.utils.DateToStamp;
import com.example.demo.utils.DbConnectionUtils;
import com.example.demo.utils.PageInfoNew;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DBConnectionServiceImpl implements DBConnectionService {

    @Resource
    DBConnectionMapper dbConnectionMapper;

    @Override
    public int save(DBConnection dbConnection) {
        dbConnection.setCreateTime(DateToStamp.getTimeStamp());
        dbConnection.setUpdateTime(DateToStamp.getTimeStamp());
        return dbConnectionMapper.insert(dbConnection);
    }

    @Override
    public int update(DBConnection dbConnection) {
        dbConnection.setUpdateTime(DateToStamp.getTimeStamp());
        return dbConnectionMapper.update(dbConnection);
    }

    @Override
    public DBConnection findById(int id) {
        return dbConnectionMapper.selectById(id);
    }

    @Override
    public List<Map<String, String>> executeQuery(int id, String sql) {
        DBConnection dbConnection = dbConnectionMapper.selectById(id);
        return DbConnectionUtils.executeQuery(DBConnectionTypeEnum.stringOfType(dbConnection.getDbType()), dbConnection.getDbConnectionUrl(), dbConnection.getDbConnectionUser(), dbConnection.getDbConnectionPassword(), sql);
    }

    @Override
    public List<DBConnection> list(int projectId) {
        return dbConnectionMapper.list(projectId);
    }

    @Override
    public PageInfoNew<DBConnection> page(Integer pageNum, Integer pageSize, Integer projectId) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfoNew<>(dbConnectionMapper.list(projectId));
    }

    @Override
    public void delete(int id) {
        dbConnectionMapper.delete(id);
    }


    @Override
    public int executeUpdate(int id, String sql) {
        DBConnection dbConnection = dbConnectionMapper.selectById(id);
        return DbConnectionUtils.executeUpdate(DBConnectionTypeEnum.stringOfType(dbConnection.getDbType()), dbConnection.getDbConnectionUrl(), dbConnection.getDbConnectionUser(), dbConnection.getDbConnectionPassword(), sql);

    }
}
